import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gourmet/color/hex.dart';
import 'package:gourmet/components/group/store.dart';
import 'package:gourmet/extensions/ex_widget.dart';
import 'package:gourmet/route/index.dart';
import 'package:gourmet/ui/keep_alive.dart';
import 'package:gourmet/ui/limited_wrap.dart';
import 'package:gourmet/ui/sliver_persistent_container.dart';
import 'package:gourmet/utils/colors.dart';
import 'package:gourmet/utils/styles.dart';
import 'package:gourmet/utils/svg.dart';
import 'package:gourmet/utils/tools.dart';

class DeliciousMainController extends GetxController {}

class DeliciousMainPage extends GetView<DeliciousMainController> {
  const DeliciousMainPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const NestedScrollPage();
  }
}

class NestedScrollPage extends StatefulWidget {
  const NestedScrollPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _NestedScrollPageState();
  }
}

class _NestedScrollPageState extends State<NestedScrollPage>
    with TickerProviderStateMixin {
  final List<String> _tabs = ['首页', '商品', '评价', '商家信息'];
  final List<String> _tags = ['免预约', '包间可用', '免费WIFI', '免费停车'];

  late TabController _tabController;

  late ScrollController _scrollController;

  double offset = 0.0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _scrollController = ScrollController()
      ..addListener(() {
        setState(() {
          offset = _scrollController.offset;
        });
      });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      context: context,
      removeBottom: true,
      removeLeft: true,
      removeRight: true,
      removeTop: true,
      child: Scaffold(
        backgroundColor: HexColor(ColorsUtils.colorF7f7),
        body: Stack(
          children: [
            SafeArea(
              child: NestedScrollView(
                controller: _scrollController,
                headerSliverBuilder:
                    (BuildContext context, bool innerBoxIsScrolled) {
                  return [
                    SliverAppBar(
                      pinned: true,
                      leading: GestureDetector(
                        onTap: Get.back,
                        child: Icon(
                          CupertinoIcons.chevron_back,
                          color: iconColor,
                          size: 20,
                        ),
                      ).paddingOnly(
                          top: Get.mediaQuery.padding.top, bottom: 10),
                      actions: [
                        GestureDetector(
                          onTap: () {},
                          child: Icon(
                            CupertinoIcons.ellipsis,
                            color: iconColor,
                            size: 20,
                          ),
                        ).paddingOnly(
                            top: Get.mediaQuery.padding.top,
                            bottom: 10,
                            right: 20),
                      ],
                      systemOverlayStyle: SystemUiOverlayStyle.dark,
                      backgroundColor: Colors.white,
                      expandedHeight: 355,
                      collapsedHeight: kToolbarHeight,
                      flexibleSpace: FlexibleSpaceBar(
                        background: Stack(
                          fit: StackFit.expand,
                          children: [
                            Column(
                              children: [
                                SizedBox(
                                  height: 200,
                                  child: Stack(
                                    children: [
                                      Image.network(
                                        'https://cdn7.axureshop.com/demo2024/1877666/images/%E5%9B%A2%E8%B4%AD%E5%BA%97%E9%93%BA_%E4%B8%BB%E9%A1%B5/u3737.jpg',
                                        height: 200,
                                        width: Get.width,
                                        fit: BoxFit.fill,
                                      ),
                                      Container(
                                        color: ColorsUtils.rgba(
                                            0, 0, 0, 0.298039215686275),
                                      )
                                    ],
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    color: HexColor(ColorsUtils.colorF7f7),
                                  ),
                                ),
                              ],
                            ),
                            Positioned(
                              width: 345,
                              height: 205,
                              left: (Get.width - 345) / 2,
                              bottom: 0,
                              child: Container(
                                decoration: const BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(10),
                                    topRight: Radius.circular(10),
                                  ),
                                ),
                                padding: const EdgeInsets.only(
                                    top: 15, left: 15, right: 15),
                                child: Column(
                                  children: [
                                    Row(
                                      children: [
                                        Column(
                                          children: [
                                            Align(
                                              alignment: Alignment.centerLeft,
                                              child: Text(
                                                '华莱士·全鸡汉堡-凤凰广场',
                                                softWrap: true,
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style:
                                                    StylesUtils.customTextStyle(
                                                  color: ColorsUtils.color0000,
                                                  fontSize:
                                                      StylesUtils.fontSize18,
                                                  fontWeight: FontWeight.w700,
                                                ),
                                              ),
                                            ),
                                            Container(
                                              margin: const EdgeInsets.only(
                                                  top: 10),
                                              alignment: Alignment.centerLeft,
                                              child: Text.rich(
                                                TextSpan(
                                                  children: [
                                                    TextSpan(
                                                      text: '4.5分  ',
                                                      style: StylesUtils
                                                          .customTextStyle(
                                                        color: ColorsUtils
                                                            .colorFf66,
                                                        fontSize: StylesUtils
                                                            .fontSize12,
                                                      ),
                                                    ),
                                                    TextSpan(
                                                      text: '西式快餐  人均￥45',
                                                      style: StylesUtils
                                                          .customTextStyle(
                                                        fontSize: StylesUtils
                                                            .fontSize12,
                                                        color: ColorsUtils
                                                            .color0000,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            )
                                          ],
                                        ).expand(flex: 1),
                                        Image.network(
                                          'https://img1.baidu.com/it/u=532906021,478561374&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=532',
                                          width: 55,
                                          height: 55,
                                          fit: BoxFit.fill,
                                        )
                                      ],
                                    ),
                                    Row(
                                      children: [
                                        Column(
                                          children: [
                                            Align(
                                              alignment: Alignment.centerLeft,
                                              child: Text(
                                                '营业时间：07:00~23:00',
                                                style:
                                                    StylesUtils.customTextStyle(
                                                  fontSize:
                                                      StylesUtils.fontSize13,
                                                  color: ColorsUtils.color0000,
                                                  fontWeight: FontWeight.w700,
                                                ),
                                              ),
                                            ),
                                            Container(
                                              margin:
                                                  const EdgeInsets.only(top: 5),
                                              alignment: Alignment.centerLeft,
                                              child: LimitedWrap(
                                                maxLine: 1,
                                                spacing: 10,
                                                children: _tags
                                                    .map(
                                                      (str) => LayoutBuilder(
                                                          builder:
                                                              (_, constraints) {
                                                        final style = StylesUtils
                                                            .customTextStyle(
                                                                fontSize:
                                                                    StylesUtils
                                                                        .fontSize12,
                                                                color: ColorsUtils
                                                                    .color9999);
                                                        final width = ToolsUtils
                                                            .calculateTextWidth(
                                                                style: style,
                                                                value: str);
                                                        return Container(
                                                          constraints:
                                                              BoxConstraints
                                                                  .expand(
                                                                      width:
                                                                          width +
                                                                              10,
                                                                      height:
                                                                          16),
                                                          decoration:
                                                              BoxDecoration(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        2),
                                                            border: Border.all(
                                                              color: HexColor(
                                                                  ColorsUtils
                                                                      .colorE4e4),
                                                            ),
                                                          ),
                                                          alignment:
                                                              Alignment.center,
                                                          child: Text(
                                                            str,
                                                            style: style,
                                                          ),
                                                        );
                                                      }),
                                                    )
                                                    .toList(),
                                              ),
                                            )
                                          ],
                                        ).flexible(),
                                        Center(
                                          child: Icon(
                                            CupertinoIcons.chevron_forward,
                                            color:
                                                HexColor(ColorsUtils.color9999),
                                            size: 12,
                                          ),
                                        )
                                      ],
                                    ).paddingOnly(top: 15),
                                    Expanded(
                                      child: Align(
                                        alignment: Alignment.bottomCenter,
                                        child: Container(
                                          height: 75,
                                          decoration: BoxDecoration(
                                            image: DecorationImage(
                                              image: ToolsUtils.assetImage(
                                                  'map_bg.jpg'),
                                              alignment: Alignment.topLeft,
                                              fit: BoxFit.fill,
                                            ),
                                          ),
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            children: [
                                              Container(
                                                width: 270,
                                                padding: const EdgeInsets.only(
                                                    top: 10, left: 15),
                                                child: Column(
                                                  children: [
                                                    Container(
                                                      alignment:
                                                          Alignment.centerLeft,
                                                      margin:
                                                          const EdgeInsets.only(
                                                              bottom: 5),
                                                      child: Text(
                                                        '北海市海城区北海大道凤凰广场A座一楼234-235号',
                                                        style: StylesUtils
                                                            .customTextStyle(
                                                                fontSize:
                                                                    StylesUtils
                                                                        .fontSize13,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .w700,
                                                                color: ColorsUtils
                                                                    .color0000,
                                                                lineHeight:
                                                                    1.3),
                                                      ),
                                                    ),
                                                    Align(
                                                      alignment:
                                                          Alignment.centerLeft,
                                                      child: Text(
                                                        '距你714m，步行约10分钟',
                                                        style: StylesUtils
                                                            .customTextStyle(
                                                                fontSize:
                                                                    StylesUtils
                                                                        .fontSize12,
                                                                color: ColorsUtils
                                                                    .color9999),
                                                      ),
                                                    )
                                                  ],
                                                ),
                                              ),
                                              Center(
                                                child: Icon(
                                                  CupertinoIcons.phone,
                                                  size: 25,
                                                  color: HexColor(
                                                      ColorsUtils.colorFf64),
                                                ),
                                              ).flexible()
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        title: Container(
                          padding: EdgeInsets.only(
                              top: Get.mediaQuery.padding.top - 2),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '华莱士·全鸡汉堡-凤凰广场',
                            softWrap: true,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: StylesUtils.textStyle(
                              fontSize: StylesUtils.fontSize16,
                              fontWeight: FontWeight.w700,
                              color: textColor,
                            ),
                          ),
                        ),
                        centerTitle: false,
                      ),
                    ),
                    SliverOverlapAbsorber(
                      handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
                          context),
                      sliver: SliverPersistentContainer(
                        pinned: true,
                        maxExtent: 60,
                        minExtent: 50,
                        child: Container(
                          color: HexColor(ColorsUtils.colorF7f7),
                          alignment: Alignment.centerLeft,
                          child: TabBar(
                            tabs: List.generate(_tabs.length, (index) {
                              return Padding(
                                padding:
                                    const EdgeInsets.symmetric(horizontal: 0),
                                child: Text(_tabs[index]),
                              );
                            }),
                            unselectedLabelColor:
                                HexColor(ColorsUtils.color0000),
                            unselectedLabelStyle: StylesUtils.customTextStyle(
                              fontSize: StylesUtils.fontSize16,
                            ),
                            labelColor: HexColor(ColorsUtils.colorFf64),
                            labelStyle: StylesUtils.customTextStyle(
                              fontSize: StylesUtils.fontSize16,
                              fontWeight: FontWeight.w700,
                            ),
                            isScrollable: false,
                            indicatorSize: TabBarIndicatorSize.label,
                            indicator: UnderlineTabIndicator(
                              borderRadius: BorderRadius.circular(3),
                              borderSide: BorderSide(
                                  color: HexColor(ColorsUtils.colorFf64),
                                  width: 3),
                              insets: const EdgeInsets.symmetric(
                                  horizontal: 3, vertical: 9),
                            ),
                            controller: _tabController,
                            dividerHeight: 0,
                            tabAlignment: TabAlignment.fill,
                            labelPadding:
                                const EdgeInsets.symmetric(vertical: 15),
                          ),
                        ),
                      ),
                    ),
                  ];
                },
                body: LayoutBuilder(
                  builder: (context, _) {
                    return Container(
                      padding: EdgeInsets.only(
                          top: NestedScrollView.sliverOverlapAbsorberHandleFor(
                                      context)
                                  .layoutExtent ??
                              0),
                      child: TabBarView(
                        controller: _tabController,
                        children: [
                          KeepAliveWrapperView(
                            child: const GroupStoreIndexView(),
                            callback: () {
                              Get.lazyPut(() => GroupStoreIndexController());
                            },
                          ),
                          KeepAliveWrapperView(
                            child: const GroupStoreProductView(),
                            callback: () {
                              Get.lazyPut(() => GroupStoreProductController());
                            },
                          ),
                          KeepAliveWrapperView(
                            child: const GroupStoreEvaluateView(),
                            callback: () {
                              Get.lazyPut(() => GroupStoreEvaluateController());
                            },
                          ),
                          KeepAliveWrapperView(
                            child: const GroupStoreInfoView(),
                            callback: () {
                              Get.lazyPut(() => GroupStoreInfoController());
                            },
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            ),
            Positioned(
              right: 12,
              bottom: 10,
              child: GestureDetector(
                onTap: () {
                  Get.toNamed(Routes.shopCart);
                },
                child: Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Container(
                      constraints:
                          BoxConstraints.expand(width: 45.w, height: 45.w),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: ToolsUtils.assetImage('u795.png'),
                        ),
                      ),
                      child:
                          SvgUtils.assetName('u247', width: 21.w, height: 22),
                    ),
                    Positioned(
                      top: 2,
                      right: 2,
                      child: Container(
                        constraints:
                            BoxConstraints.expand(width: 18.w, height: 18.w),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: ColorsUtils.parseColorFromHexString(
                              ColorsUtils.colorFf00),
                          borderRadius: BorderRadius.circular(9.w),
                        ),
                        child: Text(
                          '2',
                          style: StylesUtils.customTextStyle(
                              fontSize: StylesUtils.fontSize11),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Color get textColor {
    if (offset < kToolbarHeight) {
      return Colors.transparent;
    }
    final int alpha =
        (offset / (355 - kToolbarHeight) * 255).clamp(0, 255).toInt();
    return Color.fromARGB(alpha, 0, 0, 0);
  }

  Color get iconColor {
    if (offset < kToolbarHeight) {
      return Colors.white;
    }
    final int alpha =
        (offset / (355 - kToolbarHeight) * 255).clamp(0, 255).toInt();
    return Color.fromARGB(alpha, 0, 0, 0);
  }
}

class NestedTabBarView extends StatefulWidget {
  final TabController? controller;
  final List<Widget> children;
  final ScrollPhysics? physics;
  final DragStartBehavior dragStartBehavior;
  final double viewportFraction;
  final Clip clipBehavior;

  const NestedTabBarView({
    super.key,
    required this.children,
    this.controller,
    this.physics,
    this.dragStartBehavior = DragStartBehavior.start,
    this.viewportFraction = 1.0,
    this.clipBehavior = Clip.hardEdge,
  });

  @override
  State<StatefulWidget> createState() => _NestedTabBarViewState();
}

class _NestedTabBarViewState extends State<NestedTabBarView> {
  List<NestedInnerScrollController> _nestedInnerControllers = [];

  @override
  void initState() {
    super.initState();
    _initNestedInnerControllers();
    widget.controller?.addListener(_onTabChange);
  }

  @override
  void didUpdateWidget(covariant NestedTabBarView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.children.length != widget.children.length) {
      _initNestedInnerControllers();
    }
  }

  @override
  void dispose() {
    widget.controller?.removeListener(_onTabChange);
    _disposeNestedInnerControllers();
    super.dispose();
  }

  void _onTabChange() {
    int index = widget.controller!.index;
    if (index == widget.controller!.animation?.value) {
      _nestedInnerControllers[index].attachCurrent();
    }
  }

  void _initNestedInnerControllers() {
    _disposeNestedInnerControllers();
    List<NestedInnerScrollController> controllers =
        List.generate(widget.children.length, (index) {
      return NestedInnerScrollController();
    });

    if (mounted) {
      setState(() {
        _nestedInnerControllers = controllers;
      });
    } else {
      _nestedInnerControllers = controllers;
    }
  }

  void _disposeNestedInnerControllers() {
    for (var element in _nestedInnerControllers) {
      element.dispose();
    }
  }

  @override
  Widget build(BuildContext context) {
    return TabBarView(
      controller: widget.controller,
      physics: widget.physics,
      dragStartBehavior: widget.dragStartBehavior,
      viewportFraction: widget.viewportFraction,
      clipBehavior: widget.clipBehavior,
      children: List<Widget>.generate(
        widget.children.length,
        (index) {
          return _InheritedInnerScrollController(
            controller: _nestedInnerControllers[index],
            child: widget.children[index],
          );
        },
      ),
    );
  }
}

class _InheritedInnerScrollController extends InheritedWidget {
  final ScrollController controller;

  const _InheritedInnerScrollController(
      {required super.child, required this.controller});

  @override
  bool updateShouldNotify(
          covariant _InheritedInnerScrollController oldWidget) =>
      controller != oldWidget.controller;
}

class NestedInnerScrollController extends ScrollController {
  ScrollController? _inner;

  NestedInnerScrollController();

  @override
  ScrollPosition createScrollPosition(ScrollPhysics physics,
      ScrollContext context, ScrollPosition? oldPosition) {
    ScrollPosition scrollPosition;
    ScrollableState? scrollableState = context as ScrollableState;
    _inner = PrimaryScrollController.maybeOf(scrollableState.context);
    if (_inner == null) {
      scrollPosition =
          super.createScrollPosition(physics, context, oldPosition);
    } else {
      scrollPosition =
          _inner!.createScrollPosition(physics, context, oldPosition);
    }
    return scrollPosition;
  }

  @override
  void attach(ScrollPosition position) {
    super.attach(position);
    _inner?.attach(position);
  }

  @override
  void detach(ScrollPosition position) {
    _inner?.detach(position);
    super.detach(position);
  }

  void attachCurrent() {
    if (_inner != null) {
      while (_inner!.positions.isNotEmpty) {
        _inner!.detach(_inner!.positions.first);
      }
      _inner!.attach(position);
    }
  }

  static ScrollController of(BuildContext context) {
    final _InheritedInnerScrollController? target = context
        .dependOnInheritedWidgetOfExactType<_InheritedInnerScrollController>();
    assert(
      target != null,
      'NestedInnerScrollController.of must be called with a context that contains a NestedTabBarView\'s children.',
    );
    return target!.controller;
  }

  static ScrollController? maybeOf(BuildContext context) {
    final _InheritedInnerScrollController? target = context
        .dependOnInheritedWidgetOfExactType<_InheritedInnerScrollController>();
    return target?.controller;
  }
}
